package com.czh.springboot04.service.serviceimpl;

import com.czh.springboot04.entity.HeartMark;
import com.czh.springboot04.entity.MyTest;
import com.czh.springboot04.entity.User;
import com.czh.springboot04.mapper.HeartMarkMapper;
import com.czh.springboot04.mapper.MyTestMapper;
import com.czh.springboot04.mapper.UserMapper;
import com.czh.springboot04.service.MyTestService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyTestServiceImpl implements MyTestService {
    @Autowired
    private MyTestMapper myTestMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HeartMarkMapper heartMarkMapper;

    @Override
    public int addMyTest(MyTest myTest) {
        int j = heartMarkMapper.addHeartMark(myTest.getHeartMark());
        int k = myTestMapper.addMyTest(myTest);
        if (j > 0 && k > 0) {
            return k; // 直接返回第一次插入操作的结果
        }
        return 0;
    }
    @Override
    public int deleteMyTest(int id) {
        try {
            MyTest myTest = myTestMapper.findById(id);
            if (myTest == null) {
                return 0;
            }
            int i = userMapper.deleteUser(myTest.getUserId());
            int j = heartMarkMapper.deleteHeartMark(myTest.getTestId());
            int k = myTestMapper.deleteMyTest(id);
            if (i > 0 && j > 0 && k > 0) {
                return k; // 直接返回成功操作的结果
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
}
    @Override
    public int updateMyTest(MyTest myTest) {
        val i = userMapper.updateU(myTest.getUser());
        val j = heartMarkMapper.updateHeartMark(myTest.getHeartMark());
        int k = myTestMapper.updateMyTest(myTest);
        if (i > 0 && j > 0&&k>0) {
            return k;
        }
        return 0;
    }

    @Override
    public PageInfo <MyTest> findAll(int pageNum, int pageSize, MyTest myTest) {
        PageHelper.startPage(pageNum,pageSize);
        List<MyTest> list=myTestMapper.findAll(myTest);
        for(MyTest myTests:list){
            User user=userMapper.selectById(myTests.getUserId());
            myTests.setUser(user);
            HeartMark heartMark=heartMarkMapper.findById(myTests.getTestId());
            myTests.setHeartMark(heartMark);
        }
        PageInfo<MyTest> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }


}
